//
//  DLBaseTableViewController.m
//  DGGUIKit
//
//  Created by dgg_hzk on 2019/11/21.
//

#import "DLBaseTableViewController.h"
#import "DLBaseNavigationController.h"
#import "UIView+Extension.h"
#import "DLTableBgView.h"
#import "DLRefreshHeader.h"
#import "DLRefreshFooter.h"

NSString * const countKey = @"countKey";
NSString * const startIndexKey = @"startIndexKey";
NSString * const dataArrayKey = @"dataArrayKey";
NSString * const isLoadingKey = @"isLoadingKey";
NSString * const errorKey = @"errorKey";
NSString * const isDggTabStatusCustomKey = @"isDggTabStatusCustom";
NSString * const dggTabStatus_NoneKey = @"dggTabStatus_None";
NSString * const dggTabStatus_CustomKey = @"dggTabStatus_CustomKey";
NSString * const dggTabStatus_ErrorDictKey = @"dggTabStatus_ErrorDict";
NSString * const dggTabStatusClickKey = @"dggTabStatusClickKey";
static NSString * const bGCenterYKey = @"bGCenterYKey";

@interface DLBaseTableViewController ()


@end

@implementation DLBaseTableViewController
@synthesize dggTabStatus_ErrorDict = _dggTabStatus_ErrorDict;
@synthesize dggTabStatus_CustomDict = _dggTabStatus_CustomDict;
@synthesize dggTabStatus_NoneDict = _dggTabStatus_NoneDict;
@synthesize dggTabStatusClick = _dggTabStatusClick;
@synthesize dataArray = _dataArray;
@synthesize noDataText = _noDataText;

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    DLBaseTableViewController *tableViewController = [super allocWithZone:zone];
    
    @weakify(tableViewController)
    
    [[tableViewController rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x) {
        
        @strongify(tableViewController)
        [tableViewController dgg_addSubviews];
        [tableViewController dgg_addNavItems];
        [tableViewController dgg_setTableView];
        [tableViewController dgg_refreshControls];
        if (tableViewController.tableView.mj_header) {
            [tableViewController.tableView.mj_header beginRefreshing];
        }else {
             [tableViewController dgg_requestData];
        }
    }];
    
    [[tableViewController rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(id x) {
        
        @strongify(tableViewController)
        [tableViewController dgg_layoutNavigation];
        [tableViewController dgg_requestNewData];
    }];
    
    [[tableViewController rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        
        @strongify(tableViewController)
        [tableViewController dgg_recoverKeyboard];
    }];
    unsigned int index;
    BOOL isNumberOfSections = NO;
    BOOL isNumberOfRows = NO;
    Method *methods = class_copyMethodList([tableViewController class], &index);
    for (int i = 0; i < index; i++)
    {
        Method method = methods[i];
        SEL selector = method_getName(method);
        NSString *name = NSStringFromSelector(selector);
        if([name rangeOfString:@"numberOfSectionsInTableView:"].location !=NSNotFound)
        {
            isNumberOfSections = YES;
        }
        if([name rangeOfString:@"tableView:numberOfRowsInSection:"].location !=NSNotFound)
        {
            isNumberOfRows = YES;
        }
    }
    
    if (isNumberOfSections) {
        [[[tableViewController rac_signalForSelector:@selector(numberOfSectionsInTableView:)] delay:0.2] subscribeNext:^(id x) {
            
            @strongify(tableViewController)
            NSNumber * isLoading = objc_getAssociatedObject(tableViewController, &isLoadingKey);
            if (isLoading !=nil) {
                [tableViewController addBackgroundView];
            }
        }];
    }else if (isNumberOfRows){
        [[[tableViewController rac_signalForSelector:@selector(tableView:numberOfRowsInSection:)] delay:0.2] subscribeNext:^(id x) {
            
            @strongify(tableViewController)
            
            NSNumber * isLoading = objc_getAssociatedObject(tableViewController, &isLoadingKey);
            if (isLoading !=nil) {
                [tableViewController addBackgroundView];
            }
        }];
    }
    return tableViewController;
}
    
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self dgg_setNav];
//    if (@available(iOS 11.0, *)) {
//        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }else {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
}
- (void)dgg_setNav
{
    if (self.navigationController) {
        if ([self.navigationController isKindOfClass:[DLBaseNavigationController class]]) {
//            DLBaseNavigationController *nav = (DLBaseNavigationController*)self.navigationController;
//            [nav setNavWithViewController:self];
        }
    }
}
    
- (void)dealloc {
    NSLog(@"♦️释放♦️ %@ '%@'", NSStringFromSelector(_cmd), self.class);
}
    
/**
 添加下拉 手动调用
 */
- (void)dgg_addRefreshHeader
{
    
    kself
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.startIndex = 1;
        [weakSelf dgg_requestData];
    }];
}
    
/**
 添加上啦 手动调用
 */
- (void)dgg_addRefreshFooter
{
    
    kself
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.startIndex +=1;
        [weakSelf dgg_requestData];
    }];
    self.tableView.mj_footer.automaticallyHidden = YES;
}
    
/**
 添加上啦下拉
 */
- (void)dgg_refreshControls{}
    
/**
 设置tableView
 */
-(void)dgg_setTableView{}

/**
 添加UI
 */
- (void)dgg_addSubviews{}

/**
 设置导航 本方法每次在viewWillAppear会调用
 */
- (void)dgg_layoutNavigation{}

/**
 数据请求 本方法每次在viewWillAppear会调用
 */
- (void)dgg_requestNewData{}

/**
 数据请求 本方法在viewDidLoad会调用
 */
- (void)dgg_requestData{}
    
/**
 添加导航item
 */
- (void)dgg_addNavItems
{
    
}
    
/**
 隐藏键盘
 */
- (void)dgg_recoverKeyboard
{
    [self.view endEditing:YES];
}
    
-(void)addBackgroundView
{
    NSDictionary * dict = [self tableBackgroundViewDict];
    if (dict) {
        
         NSInteger tag = 0;
       if (dict == self.dggTabStatus_NoneDict)
        {
            tag = DGGTabStatus_None;
        }else if (dict == self.dggTabStatus_ErrorDict)
        {
            tag = DGGTabStatus_Error;
        }
        
        if (self.tableView.backgroundView .tag == tag  &&tag !=0) {
            //不做重复添加
            return;
        }
        kself
        self.tableView.backgroundView = [DLTableBgView loadNibWithImageName:dict[kDLTabStatus_imageKey]
                                                                      title:dict[kDLTabStatus_titleKey]
                                                                  isShowBtn:[dict[kDLTabStatus_isShowBtnKey] boolValue]
                                                                   btnTitle:dict[kDLTabStatus_btnTitleKey]
                                                                    content:dict[kDLTabStatus_contentKey]
                                                                    centerY:self.bGViewCenterY
                                                                buttonColor:self.navigationController.navigationBar.barTintColor
                                                                      block:^{
             weakSelf.isLoading = NO;
             weakSelf.error = NO;
             [weakSelf.tableView reloadData];
             if (weakSelf.tableView.mj_header) {
                [weakSelf.tableView.mj_header beginRefreshing];
             }else
             {
                 NSLog(@"没有mj_header  请使用self.dggTabStatusClick 监听按钮回调");
             }
             
             if (dict == weakSelf.dggTabStatus_CustomDict) {
                  [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_Custom)];
             }else if (dict == weakSelf.dggTabStatus_NoneDict)
             {
                 [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_None)];
             }else if (dict == weakSelf.dggTabStatus_ErrorDict)
             {
                 [weakSelf.dggTabStatusClick sendNext:@(DGGTabStatus_Error)];
             }
             
         }];
        self.tableView.backgroundView.tag = tag;
    }else
    {
        self.tableView.backgroundView = nil;
    }
}
    
-(NSDictionary *)tableBackgroundViewDict
{
    CGFloat height = self.tableView.sectionHeaderHeight + self.tableView.sectionFooterHeight;
    if (height <0) {
        height = 0 ;
    }
    if (self.tableView.tableHeaderView) {
        height += self.tableView.tableHeaderView.height;
        
    }
    if (self.tableView.tableFooterView) {
        height += self.tableView.tableFooterView.height;
        
    }
    for (NSInteger section = 0; section<self.tableView.numberOfSections; section++) {
        if ([self respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
            height += [self tableView:self.tableView heightForHeaderInSection:section];
        }
        if ([self respondsToSelector:@selector(tableView:heightForFooterInSection:)]) {
            height += [self tableView:self.tableView heightForFooterInSection:section];
        }
    }
    if (self.tableView.contentSize.height-height<=5 &&self.isLoading&&!self.error&&self.isDggTabStatusCustom) {
        
        return self.dggTabStatus_CustomDict;
    }else if (self.tableView.contentSize.height-height<=5  &&self.isLoading&&!self.error&&!self.isDggTabStatusCustom) {
        
        return self.dggTabStatus_NoneDict;
    }
    else if (self.tableView.contentSize.height-height<=5  &&self.isLoading&&self.error) {
        
        return self.dggTabStatus_ErrorDict;
    }else
    {
        return nil;
    }
}
    
-(NSInteger)count
{
    NSNumber * count = objc_getAssociatedObject(self, &countKey);
    if (! count)
    {
        objc_setAssociatedObject(self, &countKey, @(kCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        count = objc_getAssociatedObject(self, &countKey);
    }
    return [count integerValue];
}
    
-(void)setCount:(NSInteger)count
{
    objc_setAssociatedObject(self, &countKey, @(count), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSInteger)startIndex
{
    NSNumber * startIndex = objc_getAssociatedObject(self, &startIndexKey);
    if (! startIndex)
    {
        objc_setAssociatedObject(self, &startIndexKey, @(kStartIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        startIndex = objc_getAssociatedObject(self, &startIndexKey);
    }
    return [startIndex integerValue];
}
    
-(void)setStartIndex:(NSInteger)startIndex
{
    objc_setAssociatedObject(self, &startIndexKey, @(startIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSMutableArray*)dataArray
{
    NSMutableArray *array =  objc_getAssociatedObject(self, &dataArrayKey);
    if (!array) {
        objc_setAssociatedObject(self, &dataArrayKey, @[].mutableCopy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        array =  objc_getAssociatedObject(self, &dataArrayKey);
    }
    return array;
}
    
-(void)setDataArray:(NSMutableArray *)dataArray
{
    objc_setAssociatedObject(self, &dataArrayKey, dataArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isLoading
{
    NSNumber * isLoading = objc_getAssociatedObject(self, &isLoadingKey);
    if (!isLoading) {
        objc_setAssociatedObject(self, &isLoadingKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isLoading = objc_getAssociatedObject(self, &isLoadingKey);
    }
    return [isLoading boolValue];
}
    
-(void)setIsLoading:(BOOL)isLoading
{
    if (isLoading) {
         objc_setAssociatedObject(self, &errorKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    objc_setAssociatedObject(self, &isLoadingKey, @(isLoading), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(BOOL)error
{
    NSNumber * error = objc_getAssociatedObject(self, &errorKey);
    if (!error) {
        objc_setAssociatedObject(self, &errorKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        error = objc_getAssociatedObject(self, &errorKey);
    }
    return [error boolValue];
}
    
-(void)setError:(BOOL)error
{
    objc_setAssociatedObject(self, &errorKey, @(error), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)setNoDataText:(NSString *)noDataText
{
    _noDataText = noDataText;
    objc_setAssociatedObject(self, &dggTabStatus_NoneKey,  @{kDLTabStatus_contentKey:kFormat(noDataText).isEmpty,kDLTabStatus_imageKey:kDLTabStatus_None_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_None_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_None_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isDggTabStatusCustom
{
    NSNumber * isDggTabStatusCustom = objc_getAssociatedObject(self, &isDggTabStatusCustomKey);
    if (!isDggTabStatusCustom) {
        objc_setAssociatedObject(self, &isDggTabStatusCustomKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isDggTabStatusCustom = objc_getAssociatedObject(self, &isDggTabStatusCustomKey);
        
    }
    return [isDggTabStatusCustom boolValue];
}
    
-(void)setIsDggTabStatusCustom:(BOOL)isDggTabStatusCustom
{
    objc_setAssociatedObject(self, &isDggTabStatusCustomKey, @(isDggTabStatusCustom), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
- (CGFloat)bGViewCenterY
{
    NSNumber * bGViewCenterY = objc_getAssociatedObject(self, &bGCenterYKey);
    if (!bGViewCenterY) {
        objc_setAssociatedObject(self, &bGCenterYKey, @(0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        bGViewCenterY = objc_getAssociatedObject(self, &bGCenterYKey);
        
    }
    return [bGViewCenterY floatValue];
}
    
- (void)setBGViewCenterY:(CGFloat)bGViewCenterY
{
    objc_setAssociatedObject(self, &bGCenterYKey, @(bGViewCenterY), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(NSDictionary*)dggTabStatus_NoneDict
{
    NSDictionary *dict =  objc_getAssociatedObject(self, &dggTabStatus_NoneKey);
    if (!dict) {
        objc_setAssociatedObject(self, &dggTabStatus_NoneKey,  @{kDLTabStatus_contentKey:kDLTabStatus_None_content,kDLTabStatus_imageKey:kDLTabStatus_None_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_None_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_None_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict =  objc_getAssociatedObject(self, &dggTabStatus_NoneKey);
    }
    return dict;
}
    
-(void)setDggTabStatus_NoneDict:(NSDictionary *)dggTabStatus_NoneDict
{
    objc_setAssociatedObject(self, &dggTabStatus_NoneKey, dggTabStatus_NoneDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSMutableDictionary*)dggTabStatus_CustomDict
{
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &dggTabStatus_CustomKey);
    if (!dict) {
        objc_setAssociatedObject(self, &dggTabStatus_CustomKey, @{kDLTabStatus_contentKey:kDLTabStatus_Custom_content,kDLTabStatus_imageKey:kDLTabStatus_Custom_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_Custom_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_Custom_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_None_title}.mutableCopy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict = objc_getAssociatedObject(self, &dggTabStatus_CustomKey);
    }
    return dict;
}
    
-(void)setDggTabStatus_CustomDict:(NSMutableDictionary *)dggTabStatus_CustomDict
{
    objc_setAssociatedObject(self, &dggTabStatus_CustomKey, dggTabStatus_CustomDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSDictionary*)dggTabStatus_ErrorDict {
    NSDictionary *dict = objc_getAssociatedObject(self, &dggTabStatus_ErrorDictKey);
    if (!dict) {
        objc_setAssociatedObject(self, &dggTabStatus_ErrorDictKey, @{kDLTabStatus_contentKey:kDLTabStatus_Error_content,kDLTabStatus_imageKey:kDLTabStatus_Error_image,kDLTabStatus_isShowBtnKey:@(kDLTabStatus_Error_isShowBtn),kDLTabStatus_btnTitleKey:kDLTabStatus_Error_btnTitle,kDLTabStatus_titleKey:kDLTabStatus_Error_title}, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        dict = objc_getAssociatedObject(self, &dggTabStatus_ErrorDictKey);
    }
    return dict;
}
    
-(void)setDggTabStatus_ErrorDict:(NSDictionary *)dggTabStatus_ErrorDict
{
    objc_setAssociatedObject(self, &dggTabStatus_ErrorDictKey, dggTabStatus_ErrorDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
    
-(RACSubject*)dggTabStatusClick
{
    RACSubject *rac = objc_getAssociatedObject(self, &dggTabStatusClickKey);
    if (!rac) {
        objc_setAssociatedObject(self, &dggTabStatusClickKey,  [RACSubject subject], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        rac = objc_getAssociatedObject(self, &dggTabStatusClickKey);
    }
    return rac;
}
    
-(void)setDggTabStatusClick:(RACSubject *)dggTabStatusClick
{
    objc_setAssociatedObject(self, &dggTabStatusClickKey, dggTabStatusClick, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告");
}

#pragma mark - 下拉刷新&上拉加载

- (void)addPullDownRefreshForTableView:(UIScrollView *)tableview tintColor:(UIColor *)tintColor  completionRefreshBlock:(MJRefreshComponentRefreshingBlock)componentRefreshingBlock{
    DLRefreshHeader *refreshHeader = [DLRefreshHeader headerWithRefreshingBlock:componentRefreshingBlock];
    refreshHeader.tintColor = tintColor;
    refreshHeader.isShowTextAndCircleView = NO;
    [refreshHeader show];
    tableview.mj_header = refreshHeader;
}

- (void)addPullUpLoadMoreDataForTableView:(UIScrollView *)tableview tintColor:(UIColor *)tintColor completionRefreshBlock:(MJRefreshComponentRefreshingBlock)componentRefreshingBlock{
    
    DLRefreshFooter *refreshFooter = [DLRefreshFooter footerWithRefreshingBlock:componentRefreshingBlock];
    refreshFooter.noDataStr = @"没有更多数据";
    refreshFooter.tintColor = tintColor;
    refreshFooter.isShowTextAndCircleView = NO;
    tableview.mj_footer = refreshFooter;
    
}

- (void)endRefreshingComponentForTableView:(UIScrollView *)tableView {
    [tableView.mj_header endRefreshing];
    [tableView.mj_footer endRefreshing];
}

#pragma mark - 屏幕方向切换
//是否可以旋转
- (BOOL)shouldAutorotate{
    return NO;
}

//支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

@end
